<!--
 * @Description  :
 * @Version      : 1.0
 * @Author       : seraph
 * @Date         : 2024-12-18 16:28:00
 * @LastEditors  : seraph
 * @LastEditTime : 2025-02-18 18:18:20
-->
<template>
  <nav class="menu-container">
    <menu-items :routes="filteredRoutes" />
  </nav>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'

// 定义递归组件
const MenuItems = {
  name: 'MenuItems',
  props: {
    routes: {
      type: Array,
      required: true,
    },
  },
  setup(props) {
    const activeSubMenu = ref<string | null>(null)

    const showSubMenu = (menuName: string) => {
      activeSubMenu.value = menuName
    }

    const hideSubMenu = () => {
      activeSubMenu.value = null
    }

    return {
      activeSubMenu,
      showSubMenu,
      hideSubMenu,
    }
  },
  template: `
    <ul class="primary-menu">
      <li v-for="route in routes"
          :key="route.name"
          class="menu-item"
          @mouseleave="hideSubMenu">
        <template v-if="route.children?.length">
          <span @mouseenter="showSubMenu(route.name)">
            {{ route.meta?.title }}
          </span>
          <ul v-if="activeSubMenu === route.name" class="sub-menu">
            <menu-items :routes="route.children" />
          </ul>
        </template>
        <router-link v-else :to="route.path">
          {{ route.meta?.title }}
        </router-link>
      </li>
    </ul>
  `,
}

// 注册组件
const router = useRouter()
const filteredRoutes = computed(() => {
  return router.options.routes.filter((route) => !route.meta?.hidden && !route.redirect)
})
</script>

<style scoped>
.menu-container {
  width: 100%;
}

:deep(.primary-menu) {
  min-width: 190px;
  list-style-type: none;
  padding: 0;
  margin: 0;
}

:deep(.menu-item) {
  min-width: 150px;
  text-align: center;
  font-size: 16px;
  color: rgb(0, 19, 96);
  position: relative;
  display: inline-block;
  margin: 10px 15px;
}

:deep(.menu-item span) {
  cursor: pointer;
}

:deep(.menu-item a) {
  text-decoration: none;
  color: rgb(0, 19, 96);
  cursor: pointer;
}

:deep(.sub-menu) {
  min-width: 180px;
  list-style-type: none;
  padding: 0px;
  margin: 0;
  position: absolute;
  left: 50%;
  top: 100%;
  transform: translateX(-50%);
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1000;
}

:deep(.sub-menu-item) {
  padding: 0px;
  line-height: 200%;
}

:deep(.sub-menu-item:hover) {
  background: #f5f5f5;
}

:deep(.sub-menu-item a) {
  text-decoration: none;
  cursor: pointer;
}

/* 第一级子菜单保持在下方 */
:deep(.menu-item > .sub-menu) {
  position: absolute;
  left: 50%;
  top: 100%;
  transform: translateX(-50%);
}

/* 二级及以后的子菜单显示在右侧 */
:deep(.sub-menu .sub-menu) {
  position: absolute;
  left: 100%;
  top: 0;
  transform: translateX(0px);
  width: 180px;
}
</style>
